package com.xyht.medicine_management_system.modules.consumptionPoint.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ExceptionCast;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.modules.addresses.entity.MmsAddresses;
import com.xyht.medicine_management_system.modules.addresses.mapper.MmsAddressesMapper;
import com.xyht.medicine_management_system.modules.classification.entity.MmsMedicineClassification;
import com.xyht.medicine_management_system.modules.classification.mapper.MmsMedicineClassificationMapper;
import com.xyht.medicine_management_system.modules.consumptionPoint.constant.ConsumptionPointRecordConstant;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.MmsConsumptionPointRecord;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.MmsConsumptionPointRule;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.MmsConsumptionPointShop;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.MmsUserConsumptionPoint;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.req.MmsConsumptionPointShopReq;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.req.SimplePointShopMedicineReq;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.req.SubmitOrderByPointReq;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.resp.MmsConsumptionPointRuleResp;
import com.xyht.medicine_management_system.modules.consumptionPoint.entity.resp.MmsConsumptionPointShopResp;
import com.xyht.medicine_management_system.modules.consumptionPoint.mapper.MmsConsumptionPointRecordMapper;
import com.xyht.medicine_management_system.modules.consumptionPoint.mapper.MmsConsumptionPointRuleMapper;
import com.xyht.medicine_management_system.modules.consumptionPoint.mapper.MmsConsumptionPointShopMapper;
import com.xyht.medicine_management_system.modules.consumptionPoint.mapper.MmsUserConsumptionPointMapper;
import com.xyht.medicine_management_system.modules.consumptionPoint.service.MmsConsumptionPointShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.medicine_management_system.modules.manufacturer.entity.MmsManufacturer;
import com.xyht.medicine_management_system.modules.manufacturer.mapper.MmsManufacturerMapper;
import com.xyht.medicine_management_system.modules.medicine.constant.MedicineIsOnConstant;
import com.xyht.medicine_management_system.modules.medicine.entity.MmsMedicine;
import com.xyht.medicine_management_system.modules.medicine.entity.resp.MmsMedicineClassificationResp;
import com.xyht.medicine_management_system.modules.medicine.entity.resp.MmsMedicineDetailResp;
import com.xyht.medicine_management_system.modules.medicine.entity.resp.MmsMedicineManufacturerResp;
import com.xyht.medicine_management_system.modules.medicine.mapper.MmsMedicineMapper;
import com.xyht.medicine_management_system.modules.medicine.util.MedicineUtil;
import com.xyht.medicine_management_system.modules.order.constant.OrderConstant;
import com.xyht.medicine_management_system.modules.order.constant.OrderScheduleConstant;
import com.xyht.medicine_management_system.modules.order.entity.MmsOrder;
import com.xyht.medicine_management_system.modules.order.entity.MmsOrderSchedule;
import com.xyht.medicine_management_system.modules.order.entity.resp.OrderMedicineInfoResp;
import com.xyht.medicine_management_system.modules.order.mapper.MmsOrderMapper;
import com.xyht.medicine_management_system.modules.order.util.OrderScheduleUtil;
import com.xyht.medicine_management_system.modules.stock.entity.MmsMedicineStock;
import com.xyht.medicine_management_system.modules.stock.mapper.MmsMedicineStockMapper;
import com.xyht.medicine_management_system.modules.stock.util.MedicineStockUtil;
import com.xyht.medicine_management_system.modules.user.entity.MmsUser;
import com.xyht.medicine_management_system.modules.user.entity.resp.UserinfoResp;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.medicine_management_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.medicine_management_system.modules.consumptionPoint.constant.PointRuleStatusConstant.POINT_RULE_STATUS_ENABLE;
import static com.xyht.medicine_management_system.modules.consumptionPoint.constant.PointShopTypeConstant.POINT_SHOP_TYPE_CALCULATE;
import static com.xyht.medicine_management_system.modules.consumptionPoint.constant.PointShopTypeConstant.POINT_SHOP_TYPE_DIY;
import static com.xyht.medicine_management_system.modules.medicine.constant.MedicineIsOnConstant.MEDICINE_IS_OFF;
import static com.xyht.medicine_management_system.modules.medicine.constant.MedicineIsOnConstant.MEDICINE_IS_ON;

/**
 * <p>
 * 积分商城表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-12-07
 */
@Service
public class MmsConsumptionPointShopServiceImpl extends ServiceImpl<MmsConsumptionPointShopMapper, MmsConsumptionPointShop> implements MmsConsumptionPointShopService {
    @Resource
    private MmsMedicineMapper mmsMedicineMapper;
    @Resource
    private MmsConsumptionPointRuleMapper mmsConsumptionPointRuleMapper;
    @Resource
    private MedicineUtil medicineUtil;
    @Resource
    private MmsMedicineClassificationMapper mmsMedicineClassificationMapper;
    @Resource
    private MmsManufacturerMapper mmsManufacturerMapper;
    @Resource
    private MmsUserMapper mmsUserMapper;
    @Resource
    private MmsMedicineStockMapper medicineStockMapper;
    @Resource
    private MmsAddressesMapper mmsAddressesMapper;
    @Resource
    private MedicineStockUtil medicineStockUtil;
    @Resource
    private MmsUserConsumptionPointMapper mmsUserConsumptionPointMapper;
    @Resource
    private MmsConsumptionPointRecordMapper mmsConsumptionPointRecordMapper;
    @Resource
    private MmsOrderMapper mmsOrderMapper;
    @Resource
    private OrderScheduleUtil orderScheduleUtil;

    @Override
    public ResponseResult addConsumptionPointShop(MmsConsumptionPointShopReq pointShopReq, String userId) {
        if (isNullOrEmpty(pointShopReq.getMedicineIdList(), pointShopReq.getType())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (pointShopReq.getType() != POINT_SHOP_TYPE_DIY && pointShopReq.getType() != POINT_SHOP_TYPE_CALCULATE) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //自定义积分必须设置积分
        if (pointShopReq.getType() == POINT_SHOP_TYPE_DIY) {
            if (isNullOrEmpty(pointShopReq.getPoints())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
            if (pointShopReq.getPoints() < 0) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }
        //校验药品是否存在
        List<MmsMedicine> medicineList = mmsMedicineMapper.selectList(new LambdaQueryWrapper<MmsMedicine>()
                .in(MmsMedicine::getId, pointShopReq.getMedicineIdList())
                .eq(MmsMedicine::getIsOn, MedicineIsOnConstant.MEDICINE_IS_ON));
        if (medicineList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.MEDICINE_NOT_EXIST);
        }

        for (MmsMedicine medicine : medicineList) {
            //添加本积分商城商品
            MmsConsumptionPointShop pointShop = new MmsConsumptionPointShop();
            BeanUtils.copyProperties(pointShopReq, pointShop, "id");
            pointShop.setMedicineId(medicine.getId());

            //设置积分
            if (pointShopReq.getType() == POINT_SHOP_TYPE_CALCULATE) {
                Date nowDate = new Date();
                List<MmsConsumptionPointRule> pointRuleList = mmsConsumptionPointRuleMapper.selectList(new LambdaQueryWrapper<MmsConsumptionPointRule>()
                        .le(MmsConsumptionPointRule::getStartDate, nowDate)
                        .ge(MmsConsumptionPointRule::getEndDate, nowDate)
                        .eq(MmsConsumptionPointRule::getStatus, POINT_RULE_STATUS_ENABLE));
                if (pointRuleList.isEmpty()) {
                    return CommonResult.failed(CommonCodeEnum.POINT_RULE_NOT_AVAILABLE);
                }

                //积分运算
                Double pointsRate = pointRuleList.get(0).getPointsRate();
                BigDecimal realPrice = medicineUtil.getRealPrice(medicine.getId());
                Integer points = realPrice.multiply(BigDecimal.valueOf(pointsRate)).intValue();//运算完取整数部分
                pointShop.setPoints(points);
            }
            pointShop.setUserId(userId);
            this.save(pointShop);
        }

        return CommonResult.success();
    }

    @Override
    public ResponseResult updateConsumptionPointShop(MmsConsumptionPointShopReq pointShopReq) {
        if (isNullOrEmpty(pointShopReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (!isNullOrEmpty(pointShopReq.getType())) {
            if (pointShopReq.getType() != POINT_SHOP_TYPE_DIY && pointShopReq.getType() != POINT_SHOP_TYPE_CALCULATE) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
            //自定义积分必须设置积分
            if (pointShopReq.getType() == POINT_SHOP_TYPE_DIY) {
                if (isNullOrEmpty(pointShopReq.getPoints())) {
                    return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
                }
                if (pointShopReq.getPoints() < 0) {
                    return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
                }
            }
            //若根据规则计算积分,必须传入药品Id
            if (pointShopReq.getType() == POINT_SHOP_TYPE_CALCULATE) {
                if (pointShopReq.getMedicineIdList().isEmpty()) {
                    return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
                }
            }
        }
        MmsConsumptionPointShop pointShop = this.getById(pointShopReq.getId());
        if (isNullOrEmpty(pointShop)) {
            return CommonResult.failed(CommonCodeEnum.POINT_SHOP_NOT_EXIST);
        }
        //校验药品
        List<MmsMedicine> medicineList = new ArrayList<>();
        if (!pointShopReq.getMedicineIdList().isEmpty()) {
            medicineList = mmsMedicineMapper.selectBatchIds(pointShopReq.getMedicineIdList());
            if (medicineList.isEmpty()) {
                return CommonResult.failed(CommonCodeEnum.MEDICINE_NOT_EXIST);
            }
        }

        for (MmsMedicine medicine : medicineList) {
            //修改该条商城商品
            MmsConsumptionPointShop updPointShop = new MmsConsumptionPointShop();
            BeanUtils.copyProperties(pointShopReq, updPointShop);
            //设置积分
            if (pointShopReq.getType() == POINT_SHOP_TYPE_CALCULATE) {
                Date nowDate = new Date();
                List<MmsConsumptionPointRule> pointRuleList = mmsConsumptionPointRuleMapper.selectList(new LambdaQueryWrapper<MmsConsumptionPointRule>()
                        .le(MmsConsumptionPointRule::getStartDate, nowDate)
                        .ge(MmsConsumptionPointRule::getEndDate, nowDate)
                        .eq(MmsConsumptionPointRule::getStatus, POINT_RULE_STATUS_ENABLE));
                if (pointRuleList.isEmpty()) {
                    return CommonResult.failed(CommonCodeEnum.POINT_RULE_NOT_AVAILABLE);
                }

                //积分运算
                Double pointsRate = pointRuleList.get(0).getPointsRate();
                BigDecimal realPrice = medicineUtil.getRealPrice(medicine.getId());
                Integer points = realPrice.multiply(BigDecimal.valueOf(pointsRate)).intValue();//运算完取整数部分
                pointShop.setPoints(points);
            }
            this.updateById(updPointShop);
        }

        return CommonResult.success();
    }

    @Override
    public ResponseResult listConsumptionPointShop(Integer pageNum, Integer pageSize, Integer status, String searchStr) {
        LambdaQueryWrapper<MmsConsumptionPointShop> pointShopQueryWrapper = new LambdaQueryWrapper<MmsConsumptionPointShop>()
                .orderByDesc(MmsConsumptionPointShop::getUpdateTime);

        //构造商品查询条件
        LambdaQueryWrapper<MmsMedicine> medicineQueryWrapper = new LambdaQueryWrapper<>();
        //商城商品启用状态
        if (!isNullOrEmpty(status)) {
            if (status != MEDICINE_IS_ON && status != MEDICINE_IS_OFF) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
            medicineQueryWrapper.eq(MmsMedicine::getIsOn, status);
        }
        //搜索字符串
        if (!isNullOrEmpty(searchStr)) {
            StringUtils.deleteWhitespace(searchStr);
            medicineQueryWrapper.like(MmsMedicine::getCommonNames, searchStr).or()
                    .like(MmsMedicine::getEnglishName, searchStr).or()
                    .like(MmsMedicine::getManufacturer, searchStr).or()
                    .like(MmsMedicine::getBrand, searchStr).or()
                    .like(MmsMedicine::getFunctionalIndications, searchStr).or()
                    .like(MmsMedicine::getMainComponents, searchStr).or()
                    .like(MmsMedicine::getProductIntroduction, searchStr);
        }

        List<MmsMedicine> medicineList = mmsMedicineMapper.selectList(medicineQueryWrapper);
        if (!medicineList.isEmpty()) {
            List<String> medicineIdList = medicineList.stream().distinct().map(MmsMedicine::getId).collect(Collectors.toList());
            pointShopQueryWrapper.in(MmsConsumptionPointShop::getMedicineId, medicineIdList);
        }

        Page<MmsConsumptionPointShop> page = new Page<>(pageNum, pageSize);
        this.page(page, pointShopQueryWrapper);

        List<MmsConsumptionPointShopResp> pointShopRespList = page.getRecords().stream().map(pointShop -> {
            MmsConsumptionPointShopResp pointShopResp = new MmsConsumptionPointShopResp();
            BeanUtils.copyProperties(pointShop, pointShopResp);
            //设置药品详情
            MmsMedicineDetailResp medicineDetailResp = new MmsMedicineDetailResp();
            MmsMedicine medicine = mmsMedicineMapper.selectById(pointShop.getMedicineId());
            if (!isNullOrEmpty(medicine)) {
                BeanUtils.copyProperties(medicine, medicineDetailResp);
            }
            pointShopResp.setMedicineDetailResp(medicineDetailResp);

            return pointShopResp;
        }).collect(Collectors.toList());

        return CommonResult.success(pointShopRespList, (int) page.getTotal());
    }

    @Override
    public ResponseResult pointShopDetail(String pointShopId) {
        if (isNullOrEmpty(pointShopId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        MmsConsumptionPointShop pointShop = this.getById(pointShopId);
        if (isNullOrEmpty(pointShop)) {
            return CommonResult.failed(CommonCodeEnum.POINT_SHOP_NOT_EXIST);
        }

        // 商品积分信息
        MmsConsumptionPointShopResp pointShopResp = new MmsConsumptionPointShopResp();
        BeanUtils.copyProperties(pointShop, pointShopResp);

        // 药品信息
        MmsMedicine medicine = mmsMedicineMapper.selectById(pointShop.getMedicineId());
        if (medicine == null) {
            return CommonResult.failed(CommonCodeEnum.MEDICINE_NOT_EXIST);
        }

        // 构造返回数据
        MmsMedicineDetailResp medicineDetailResp = new MmsMedicineDetailResp();
        BeanUtils.copyProperties(medicine, medicineDetailResp);
        // 库存
        List<MmsMedicineStock> medicineStockList = medicineStockMapper.selectList(new LambdaQueryWrapper<MmsMedicineStock>()
                .eq(MmsMedicineStock::getMedicineId, medicine.getId()));
        if (medicineStockList.isEmpty()) {
            medicineDetailResp.setStockQuantity(0);
        } else {
            medicineDetailResp.setStockQuantity(medicineStockList.get(0).getStockQuantity());
        }

        // 分类
        MmsMedicineClassification medicineClassification = mmsMedicineClassificationMapper.selectById(medicine.getClassificationId());
        if (!isNullOrEmpty(medicineClassification)) {
            MmsMedicineClassificationResp classificationResp = new MmsMedicineClassificationResp();
            BeanUtils.copyProperties(medicineClassification, classificationResp);
            medicineDetailResp.setClassificationInfo(classificationResp);
        }

        // 厂家
        MmsManufacturer mmsManufacturer = mmsManufacturerMapper.selectById(medicine.getManufacturer());
        if (!isNullOrEmpty(mmsManufacturer)) {
            MmsMedicineManufacturerResp manufacturerResp = new MmsMedicineManufacturerResp();
            BeanUtils.copyProperties(mmsManufacturer, manufacturerResp);
            medicineDetailResp.setManufacturerInfo(manufacturerResp);
        }
        pointShopResp.setMedicineDetailResp(medicineDetailResp);


        // 积分规则信息
        MmsConsumptionPointRule pointRule = mmsConsumptionPointRuleMapper.selectById(pointShop.getRuleId());
        if (!isNullOrEmpty(pointRule)) {
            MmsConsumptionPointRuleResp ruleResp = new MmsConsumptionPointRuleResp();
            BeanUtils.copyProperties(pointRule, ruleResp);
            pointShopResp.setRuleResp(ruleResp);
        }

        // 创建人信息
        MmsUser user = mmsUserMapper.selectById(pointShop.getUserId());
        if (!isNullOrEmpty(user)) {
            UserinfoResp userinfoResp = new UserinfoResp();
            BeanUtils.copyProperties(user, userinfoResp);
            pointShopResp.setUserinfoResp(userinfoResp);
        }

        return CommonResult.success(pointShopResp);
    }

    @Override
    @Transactional
    public ResponseResult submitOrderByPoint(SubmitOrderByPointReq orderReq, String userId) {
        // 使用积分提交订单
        if (isNullOrEmpty(orderReq.getSimpleMedicineList(), orderReq.getAddressId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        // 校验当前用户地址是否存在
        List<MmsAddresses> addressList = mmsAddressesMapper.selectList(new LambdaQueryWrapper<MmsAddresses>()
                .eq(MmsAddresses::getId, orderReq.getAddressId())
                .eq(MmsAddresses::getUserId, userId));
        if (addressList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.ADDRESS_NOT_EXIST);
        }

        // 校验药品是否可售卖 并 计算总积分
        int totalPoints = 0;
        List<OrderMedicineInfoResp> medicineInfoRespList = new ArrayList<>();
        for (SimplePointShopMedicineReq simplePointShopMedicineReq : orderReq.getSimpleMedicineList()) {
            // 药品id, 数量 必填
            if (isNullOrEmpty(simplePointShopMedicineReq.getShopMedicineId(), simplePointShopMedicineReq.getMedicineNum())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }

            // 数量必须大于0
            if (simplePointShopMedicineReq.getMedicineNum() <= 0) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }

            // 校验药品是否存在
            MmsConsumptionPointShop pointShopMedicine = this.getById(simplePointShopMedicineReq.getShopMedicineId());
            if (isNullOrEmpty(pointShopMedicine)) {
                return CommonResult.failed(CommonCodeEnum.POINT_SHOP_NOT_EXIST);
            }
            MmsMedicine medicine = mmsMedicineMapper.selectById(pointShopMedicine.getMedicineId());
            if (isNullOrEmpty(medicine)) {
                return CommonResult.failed(CommonCodeEnum.MEDICINE_NOT_EXIST);
            }

            // 校验是否上架
            if (medicine.getIsOn() != MedicineIsOnConstant.MEDICINE_IS_ON) {
                return CommonResult.failed(CommonCodeEnum.MEDICINE_IS_OFF);
            }

            // 校验药品库存并减少库存
            if (medicineStockUtil.getMedicineStock(medicine.getId()) < simplePointShopMedicineReq.getMedicineNum()) {
                return CommonResult.failed(CommonCodeEnum.ORDER_MEDICINE_OUT_OF_STOCK);
            }
            boolean reduceSuccess = medicineStockUtil.reduceMedicineStock(medicine.getId(), simplePointShopMedicineReq.getMedicineNum(), userId);
            if (!reduceSuccess) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ORDER_MEDICINE_REDUCE_STOCK_FAIL));
            }

            // 累加积分
            totalPoints = totalPoints + pointShopMedicine.getPoints();

            // 收集药品信息
            OrderMedicineInfoResp medicineInfoResp = new OrderMedicineInfoResp();
            medicineInfoResp.setMedicine(medicine);
            medicineInfoResp.setMedicineNum(simplePointShopMedicineReq.getMedicineNum());
            medicineInfoRespList.add(medicineInfoResp);
        }

        // 校验用户积分是否足够
        List<MmsUserConsumptionPoint> userPointsList = mmsUserConsumptionPointMapper.selectList(new LambdaQueryWrapper<MmsUserConsumptionPoint>()
                .eq(MmsUserConsumptionPoint::getUserId, userId));
        MmsUserConsumptionPoint userPoint;
        if (userPointsList.isEmpty()) {
            userPoint = new MmsUserConsumptionPoint();
            userPoint.setUserId(userId);
            userPoint.setPoints(0);
            mmsUserConsumptionPointMapper.insert(userPoint);
        } else {
            userPoint = userPointsList.get(0);
        }
        if (userPoint.getPoints() < totalPoints) {
            return CommonResult.failed(CommonCodeEnum.POINT_USER_POINT_NOT_ENOUGH);
        }

        // 修改用户剩余积分
        int nowPoints = userPoint.getPoints() - totalPoints;
        userPoint.setPoints(nowPoints);
        mmsUserConsumptionPointMapper.updateById(userPoint);

        // 初始化订单
        MmsOrder order = new MmsOrder();
        BeanUtils.copyProperties(orderReq, order);
        order.setUserId(userId);
        order.setMedicineInfo(JSON.toJSONString(medicineInfoRespList)); // 设置药品信息
        order.setOrderStatus(OrderConstant.ORDER_STATUS_TO_BE_DELIVERED); // 待发货
        order.setIsRefund(OrderConstant.ORDER_IS_REFUND_NO); // 不存在售后/退款
        order.setIsRefunding(false); // 不在售后中
        order.setIsClose(OrderConstant.ORDER_IS_CLOSE_NO); // 没有结束
        order.setIsAbnormal(false); // 订单正常
        order.setAddressInfo(JSON.toJSONString(addressList.get(0))); // 设置地址信息
        order.setTotalAmount(new BigDecimal(0));
        order.setPaymentAmount(new BigDecimal(0));
        order.setPaymentMethod(OrderConstant.ORDER_PAYMENT_METHOD_CONSUMPTION_POINT); // 积分兑换
        order.setPaymentTime(new Date());
        order.setIsUsePoint(true);
        // 设置订单类型
        if (isNullOrEmpty(orderReq.getType())) {
            order.setType(OrderConstant.ORDER_TYPE_COMMON); // 普通订单
        }
        // 设置订单级别
        if (isNullOrEmpty(orderReq.getType())) {
            order.setOrderLevel(OrderConstant.ORDER_LEVEL_COMMON); // 普通订单
        }
        mmsOrderMapper.insert(order);

        // 创建订单定时任务
        MmsOrderSchedule orderSchedule = orderScheduleUtil.generateOrderScheduleByType(order.getId(), OrderScheduleConstant.ORDER_SCHEDULE_TYPE_DELIVERY, userId);
        if (orderSchedule == null) {
            return CommonResult.failed(CommonCodeEnum.ORDER_SCHEDULE_GENERATION_FAILED);
        }

        // 添加用户消费记录
        MmsConsumptionPointRecord pointRecord = new MmsConsumptionPointRecord();
        pointRecord.setUserId(userId);
        pointRecord.setOrderId(order.getId());
        pointRecord.setAmount(new BigDecimal(0));
        pointRecord.setPoints(totalPoints);
        pointRecord.setStatus(ConsumptionPointRecordConstant.POINT_RECORD_STATUS_REDUCE);
        pointRecord.setType(ConsumptionPointRecordConstant.POINT_RECORD_TYPE_PURCHASE);
        pointRecord.setMedicineInfo(order.getMedicineInfo());
        pointRecord.setPaymentMethod(order.getPaymentMethod());
        mmsConsumptionPointRecordMapper.insert(pointRecord);

        // 订单中记录消费记录
        order.setPointRecordId(pointRecord.getId());
        mmsOrderMapper.updateById(order);

        return CommonResult.success();
    }
}
